package com.sixks.app.mvc.cmd;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author colin
 * @date: 02/03/2014
 * @time: 13:06
 */
public class UploadPhoneBankFile {


    public static final String URL = "http://gw.api.alibaba.com/fileapi/param2/1/aliexpress.open/api.uploadImage/5754679?access_token=f1cb04fa-2f3d-4d09-afde-e0afff5c2fb7&fileName=20140302.jpg";

    public static void main(String args[]) {


        File file = new File("/Users/colin/Downloads/test.jpg");
        try {
            String result = submit(URL, null, file, "gb2312");
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String submit(String url, String fileName, File file, String charset) throws Exception {
        HttpClient client = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader("Content-type", "application/octet-stream");


        byte[] content = FileUtils.readFileToByteArray(file);
        postMethod.setRequestEntity(new ByteArrayRequestEntity(content));


        try {
            int statusCode = client.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Not 200");
            }
            InputStream in = postMethod.getResponseBodyAsStream();
            return new String(IOUtils.toByteArray(in), charset);


        } catch (IOException e) {
            return null;
        } finally {
            postMethod.releaseConnection();
        }
    }


}